package com.hlf.modules.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.hlf.common.constants.Constants;
import com.hlf.common.exception.BusinessException;
import com.hlf.common.utils.IdWorkerFactory;
import com.hlf.common.utils.PageUtils;
import com.hlf.common.utils.Query;
import com.hlf.common.utils.ReturnResult;
import com.hlf.modules.api.entity.Print;
import com.hlf.modules.api.entity.PrintDTO;
import com.hlf.modules.api.mapper.PrintMapper;
import com.hlf.modules.api.service.MachineService;
import com.hlf.modules.sys.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/10/27.
 * 设备实现类
 */
@Service
public class MachineServiceImpl implements MachineService {

    @Autowired
    private PrintMapper printMapper;

    /**
     * 打印机列表
     *
     * @param
     * @return
     */
    @Override
    public PageUtils queryPrintList(SysUserEntity user, Map<String, Object> param) {
        String url = "http://open.printcenter.cn:8080/queryPrinterStatus";
        Long storeId = Long.valueOf(user.getCurrentStoreId());
        Long userId = user.getUserId();
        List<Print> printList = printMapper.selectListByStoreId(storeId, userId);
//        获取最新状态
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        RestTemplate restTemplate = new RestTemplate();

        for (Print print : printList) {
            params.add("deviceNo", print.getMachineNum());
            params.add("key", print.getPrintKey());
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);
            String result = restTemplate.postForObject(url, request, String.class);
            PrintDTO printDTO = JSON.parseObject(result, PrintDTO.class);
            String printStatus = print.getPrintStatus();
            String responseCode = printDTO.getResponseCode();
            Integer responseCodeInt = Integer.valueOf(responseCode);
            if (responseCode.equals(printStatus)) {
                continue;
            }
            switch (responseCodeInt) {
                case Constants.PRINT_STATUS_TYPE_ONLINE:
                    print.setPrintStatus(responseCode);
                    print.setPrintStatusInfo("在线");
                    break;
                case Constants.PRINT_STATUS_TYPE_LACK:
                    print.setPrintStatus(responseCode);
                    print.setPrintStatusInfo("缺纸");
                    break;
                case Constants.PRINT_STATUS_TYPE_DOWNLINE:
                    print.setPrintStatus(responseCode);
                    print.setPrintStatusInfo("下线");
                    break;
                default:
                    print.setPrintStatus("0");
                    print.setPrintStatusInfo("未知");
            }
            print.setLastUpdateBy(user.getUserId());
            printMapper.updateByPrimaryKeySelective(print);
        }

        param.put("userId", userId);
        param.put("storeId", storeId);
        Query query = new Query(param);
        int i = printMapper.queryTotal(query);
        if (i > 0) {
            printList = printMapper.queryList(query);
        } else {
            return null;
        }
        PageUtils pageUtils = new PageUtils(printList, i, query.getLimit(), query.getPage());
        return pageUtils;
    }

    /**
     * 添加打印机
     *
     * @return
     */
    @Override
    public ReturnResult addPrint(SysUserEntity user, Print print) {

        //检查打印机是否已绑定
        int j = printMapper.selectCountByMachineNum(print.getMachineNum());
        if (j != 0) {
            return ReturnResult.error("打印机已绑定!");
        }
        //打印数量不能超过2
        Integer printNumInt = Integer.valueOf(print.getPrintNum());
        if (printNumInt > 2) {
            return ReturnResult.error("打印数量不能超过两张!");
        }
        print.setId(IdWorkerFactory.nextId());
        print.setStoreId(Long.valueOf(user.getCurrentStoreId()));
        print.setInsertBy(user.getUserId());
        int i = printMapper.insertSelective(print);
        if (i == 0) {
            return ReturnResult.error("抱歉,打印机添加失败!");
        }
        return ReturnResult.ok();
    }

    /**
     * 修改打印机使用状态
     *
     * @param user
     */
    @Override
    public void useOrFree(SysUserEntity user, Print print) {

        Byte useFlag = print.getUseStatus();
        print.setLastUpdateBy(user.getUserId());
        if (Constants.PRINT_USE_STATUS_FREE.equals(useFlag)) {
            print.setDelFlag(Constants.DELETE_FLAG_UNABLE);
        }
        int i = printMapper.updateByPrimaryKeySelective(print);
        if (i == 0) {
            throw new BusinessException("更新失败!");
        }


    }

    /**
     * 查询单个打印机
     *
     * @param id
     * @return
     */
    @Override
    public Print queryObject(long id) {
        return printMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Print> queryList(Long storeId,Long userId) {
        return printMapper.selectListByStoreId(storeId,userId);
    }
}
